package org.linlinjava.litemall.web.annotation.support;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.linlinjava.litemall.core.config.DynamicTimeZoneConfiguration;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallToken;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.linlinjava.litemall.db.service.LitemallTokenService;
import org.linlinjava.litemall.db.util.SpringUtils;
import org.linlinjava.litemall.web.annotation.LoginShop;
import org.linlinjava.litemall.web.service.UserTokenManager;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


public class LoginShopHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    public static final String LOGIN_TOKEN_KEY = "I-Lumiere-Token";
    private DynamicTimeZoneConfiguration dynamicTimeZoneConfiguration = new DynamicTimeZoneConfiguration();

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(LoginShop.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
//        return new Integer(1);
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            return null;
        }
        Integer shopId = UserTokenManager.getShopId(token);

        //动态设置门店时区
        LitemallShopService shopService = (LitemallShopService) SpringUtils.getBean("litemallShopService");
        LitemallShop shop = shopService.findById(shopId);
        dynamicTimeZoneConfiguration.setDynamicTimeZone(shop.getTimezone());
        return shopId;
    }
}
